<template>
  <div class="login-container">
    <el-row>
      <el-col :lg="14" :md="11" :sm="24" :xl="14" :xs="24">
        <div style="color: transparent">占位符</div>
      </el-col>
      <el-col :lg="9" :md="12" :sm="24" :xl="9" :xs="24">
        <el-form
          v-show="logintype == 'accpwd'"
          ref="formRef"
          class="login-form"
          label-position="left"
          :model="form"
          :rules="rules"
        >
          <!-- <div class="title">hello !</div> -->
          <div class="title-tips">
            {{ translateTitle('欢迎使用') }}{{ title }}！
          </div>
          <el-form-item prop="username">
            <el-input
              v-model.trim="form.username"
              v-focus
              :placeholder="translateTitle('请输入用户名')"
              tabindex="1"
              type="text"
              maxlength="12"
            >
              <template #prefix>
                <vab-icon icon="user-line" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              :key="passwordType"
              ref="passwordRef"
              v-model.trim="form.password"
              :placeholder="translateTitle('请输入密码')"
              tabindex="2"
              :type="passwordType"
              @keyup.enter="handleLogin"
            >
              <template #prefix>
                <vab-icon icon="lock-line" />
              </template>
              <template v-if="passwordType === 'password'" #suffix>
                <vab-icon
                  class="show-password"
                  icon="eye-off-line"
                  @click="handlePassword"
                />
              </template>
              <template v-else #suffix>
                <vab-icon
                  class="show-password"
                  icon="eye-line"
                  @click="handlePassword"
                />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="verificationCode">
            <el-input
              v-model.trim="form.verificationCode"
              :placeholder="translateTitle('验证码') + previewText"
              tabindex="3"
              type="text"
            >
              <template #prefix>
                <vab-icon icon="barcode-box-line" />
              </template>
            </el-input>
            <el-image class="code" :src="codeUrl" @click="changeCode" />
          </el-form-item>
          <el-form-item>
            <el-button
              class="login-btn"
              :loading="loading"
              type="primary"
              @click="handleLogin"
            >
              {{ translateTitle('账号密码登录') }}
            </el-button>
            <div
              style="margin-left: 50px; color: #fff; cursor: pointer"
              @click="qiehuanlogin('dingtalk')"
            >
              {{ translateTitle('使用钉钉扫码登录') }}
            </div>
          </el-form-item>
          <!-- <el-form-item>
            <router-link to="/register">
              {{ translateTitle('注册') }}
            </router-link>
          </el-form-item> -->
        </el-form>
        <el-form
          v-show="logintype == 'dingtalk'"
          ref="formRef"
          class="login-form"
          label-position="left"
          :model="form"
          :rules="rules"
        >
          <!-- <div class="title">hello !</div> -->
          <div class="title-tips">
            {{ translateTitle('欢迎使用') }}{{ title }}！
          </div>
          <el-form-item prop="username">
            <div
              style="
                width: 100%;
                display: flex;
                align-items: center;
                justify-content: center;
                flex-direction: column;
              "
            >
              <div
                id="dd_login"
                style="margin: 0 auto; width: 280px; height: 280px"
              ></div>
              <div style="color: white">钉钉扫码登录</div>
            </div>
          </el-form-item>
          <el-form-item>
            <!-- <el-button
              class="login-btn"
              :loading="loading"
              type="primary"
              @click="handleLogin"
            >
              {{ translateTitle('使用钉钉登录') }}
            </el-button> -->
            <div
              v-if="loginT"
              style="color: #fff; width: 100%; text-align: center"
              @click="qiehuanlogin('accpwd')"
            >
              {{ translateTitle('使用账号密码登录') }}
            </div>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :lg="1" :md="1" :sm="24" :xl="1" :xs="24">
        <div style="color: transparent">占位符</div>
      </el-col>
    </el-row>
    <vab-footer />
  </div>
</template>

<script>
  import { useSettingsStore } from '@/store/modules/settings'
  import { useUserStore } from '@/store/modules/user'
  import { translate } from '@/i18n'
  import { isPassword } from '@/utils/validate'

  export default defineComponent({
    name: 'Login',

    directives: {
      focus: {
        mounted(el) {
          el.querySelector('input').focus()
        },
      },
    },
    setup() {
      const route = useRoute()
      const router = useRouter()

      const userStore = useUserStore()
      const settingsStore = useSettingsStore()

      const login = (form) => userStore.login(form)
      const dingtalkLogin = (dingForm) => userStore.dingtalkLogin(dingForm)

      const validateUsername = (rule, value, callback) => {
        if ('' === value) callback(new Error(translate('用户名不能为空')))
        else callback()
      }
      const validatePassword = (rule, value, callback) => {
        if (!isPassword(value))
          callback(new Error(translate('密码不能少于6位')))
        else callback()
      }

      const state = reactive({
        appKey: 'dingbgbhvnlc84inza6a',
        // appKey: 'dingsb8cjalztdbmi13m',
        dingRedirectUrl: encodeURIComponent('https://erp.sanjianke.com'),
        // dingRedirectUrl: encodeURIComponent('http://erp.sanjin.comdns.cn'),
        logintype: 'dingtalk',
        formRef: null,
        passwordRef: null,
        dingForm: {
          authCode: '',
        },
        form: {
          username: '',
          password: '',
          verificationCode: '',
        },
        rules: {
          username: [
            {
              required: true,
              trigger: 'blur',
              validator: validateUsername,
            },
          ],
          password: [
            {
              required: true,
              trigger: 'blur',
              validator: validatePassword,
            },
          ],
          verificationCode: [
            {
              required: true,
              trigger: 'blur',
              message: '验证码不能空',
            },
          ],
        },
        loading: false,
        passwordType: 'password',
        redirect: undefined,
        timer: 0,
        codeUrl: 'https://www.oschina.net/action/user/captcha',
        previewText: '',
        loginT: false,
      })

      const qiehuanlogin = (logintype) => {
        state.logintype = logintype
        // if (logintype == 'dingtalk') {
        //   nextTick(() => {
        //     ddLogin()
        //   })
        // }
      }

      const handleRoute = () => {
        return state.redirect === '/404' || state.redirect === '/403'
          ? '/'
          : state.redirect
      }
      const handlePassword = () => {
        state.passwordType === 'password'
          ? (state.passwordType = '')
          : (state.passwordType = 'password')
        nextTick(() => {
          state['passwordRef'].focus()
        })
      }
      const handleLogin = async () => {
        state['formRef'].validate(async (valid) => {
          if (valid)
            try {
              state.loading = true
              await login(state.form).catch(() => {})
              await router.push(handleRoute())
            } finally {
              state.loading = false
            }
        })
      }
      const changeCode = () => {
        state.codeUrl = `https://www.oschina.net/action/user/captcha?timestamp=${new Date().getTime()}`
      }

      // 国家法律法规要求显示备案号 实际项目请自行为自己的备案信息及域名
      // const beianShow = ref(false)

      onBeforeMount(() => {
        // state.form.username = 'admin'
        // state.form.password = '123456'
        // // 为了演示效果，会在官网演示页自动登录到首页，正式开发可删除
        // if (
        //   location.hostname === 'vue-admin-beautiful.com' ||
        //   location.hostname === 'chu1204505056.gitee.io'
        // ) {
        //   beianShow.value = true
        //   state.previewText = '（演示地址验证码可不填）'
        //   state.timer = setTimeout(() => {
        //     handleLogin()
        //   }, 5000)
        // }
      })

      watchEffect(() => {
        state.redirect = (route.query && route.query.redirect) || '/'
      })

      onBeforeRouteLeave((to, from, next) => {
        clearInterval(state.timer)
        next()
      })
      onMounted(() => {
        if (route.query.t) {
          state.loginT = true
          state.logintype = 'accpwd'
        }
        ddLogin()
      })

      const ddLogin = () => {
        // const url = state.dingRedirectUrl
        window.DTFrameLogin(
          {
            id: 'dd_login',
            width: 280,
            height: 280,
          },
          {
            redirect_uri: state.dingRedirectUrl, //必须和钉钉后台配置的重定向域名一致，这里也可以改成域名，重定向URL也要和浏览器访问的地址保持一致，不然扫码后无反应。
            client_id: state.appKey,
            scope: 'openid',
            response_type: 'code',
            state: randomString(10),
            prompt: 'consent',
          },
          async (loginResult) => {
            const { redirectUrl, authCode } = loginResult
            console.log('loginResult', redirectUrl, authCode)

            state.dingForm = {
              authCode: authCode,
            }
            await dingtalkLogin(state.dingForm).catch(() => {})
            window.location.href = '/#/index'
            // router.push('/')
            // 根据后端提供的接口，向后端传递临时授权码使，用code进行授权
            // try {
            //   state.loading = true
            //   // await dingtalkLogin(getParams).catch(() => {})
            //   await router.push('/')
            // } finally {
            //   state.loading = false
            // }
          },
          (errorMsg) => {
            // 这里一般需要展示登录失败的具体原因
            console.log(errorMsg, '走了几遍errorMsg')
            alert(`Login Error: ${errorMsg}`)
          }
        )
      }
      const randomString = (len) => {
        len = len || 10
        const $chars = 'ABCDEFGHIJKMNOPQRSTUVWXYZ' // 默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1
        const maxPos = $chars.length
        let pwd = ''
        for (let i = 0; i < len; i++) {
          pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
        }
        console.log(pwd, 'pwd')

        return pwd
      }

      return {
        translateTitle: translate,
        ...toRefs(state),
        title: settingsStore.getTitle,
        randomString,
        qiehuanlogin,
        ddLogin,
        handlePassword,
        handleLogin,
        changeCode,
      }
    },
  })
</script>

<style lang="scss" scoped>
  .login-container {
    height: 100vh;
    background: url('~@/assets/login_images/background.jpg') center center fixed
      no-repeat;
    background-size: cover;

    .login-form {
      position: relative;
      max-width: 100%;
      padding: 4.5vh;
      margin: calc((100vh - 555px) / 2) 5vw 5vw;
      overflow: hidden;
      background: url('~@/assets/login_images/login_form.png');
      background-size: 100% 100%;

      .title {
        font-size: 54px;
        font-weight: 500;
        color: var(--el-color-white);
      }

      .title-tips {
        margin-top: 29px;
        font-size: 26px;
        font-weight: 400;
        color: var(--el-color-white);
      }

      .login-btn {
        display: inherit;
        width: 180px;
        height: 50px;
        margin-top: 5px;
        background: var(--el-color-primary);
        border: 0;

        &:hover {
          opacity: 0.9;
        }
      }

      .tips {
        margin-bottom: 10px;
        font-size: $base-font-size-default;
        color: var(--el-color-white);

        span {
          &:first-of-type {
            margin-right: 16px;
          }
        }
      }

      .title-container {
        position: relative;

        .title {
          margin: 0 auto 40px;
          font-size: 34px;
          font-weight: bold;
          color: var(--el-color-primary);
          text-align: center;
        }
      }

      i {
        position: absolute;
        top: 8px;
        left: 15px;
        font-size: 16px;
      }

      .show-password {
        float: right;
        width: 32px;
        height: 32px;
        font-size: 16px;
      }

      :deep() {
        .el-form-item {
          padding-right: 0;
          margin: 20px 0;
          color: #454545;
          background: transparent;
          border: 1px solid transparent;
          border-radius: 2px;

          &__content {
            min-height: $base-input-height;
            line-height: $base-input-height;
          }

          &__error {
            position: absolute;
            top: 100%;
            left: 18px;
            font-size: $base-font-size-small;
            line-height: 18px;
            color: var(--el-color-error);
          }
        }

        .el-input {
          box-sizing: border-box;

          input {
            height: 48px;
            padding-left: 30px;
            line-height: 48px;
            border: 0;
          }

          &__suffix-inner {
            position: absolute;
            right: 65px;
            cursor: pointer;
          }
        }

        .code {
          position: absolute;
          top: 4px;
          right: 4px;
          cursor: pointer;
          border-radius: $base-border-radius;
        }
      }
    }

    :deep() {
      .vab-footer {
        position: fixed;
        bottom: 20px;
        width: 100%;
        color: #fff !important;
        text-align: center;
        background: transparent;
        border: 0;
      }
    }
  }
</style>
